package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.UserInsert;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserInfoVO;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @RestController注解：
 * 1.组合注解，相当于@Controller注解和@ResponseBody注解的组合；
 * 2.加完此注解后，所有的方法上都不需要再添加ResponseBody注解；
 */
//@Controller
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    //自动装配
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("添加用户功能")
    @PostMapping("insert")
    public JsonResult insert(@Validated UserInsert userInsert){
        log.debug("userInsert = " + userInsert);
        User user = new User();
        //复制属性
        BeanUtils.copyProperties(userInsert,user);
        user.setCreated(new Date());
        log.debug("user = " + user);
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    @ApiOperation("查询用户列表功能")
    @GetMapping("userList")
    public List<UserListVO> userList(){
        List<UserListVO> userListVO = userMapper.selectUserListVO();
        return userListVO;
    }
    @ApiOperation("删除用户功能")
    @GetMapping("delete")
    @ApiImplicitParam(name = "id",value = "用户编号",required = true,dataType = "int")
    public JsonResult delete(@Range(min = 1,max = 100,message = "用户id范围在1-100之间") @RequestParam int id){
        log.debug("id = " + id);
        userMapper.deleteUserById(id);
        return JsonResult.ok();
    }
    @ApiOperation("修改用户功能")
    @PostMapping("update")
    private JsonResult update(User user){
        log.debug("user = " + user);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }
    @ApiOperation("根据id查询用户信息")
    @GetMapping("{id}")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "用户编号",required = true,
            dataType = "int"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,
            dataType = "string")
    })
    public UserInfoVO userInfoVO(@PathVariable int id){
        log.debug("id = " + id);
        return userMapper.selectUserinfoById(id);
    }

}
